// 获取DOM元素
const elements = {
  toggleBtn: document.getElementById('toggleBtn'),
  statusElement: document.getElementById('status'),
  densitySlider: document.getElementById('density'),
  densityValue: document.getElementById('densityValue'),
  speedSlider: document.getElementById('speed'),
  speedValue: document.getElementById('speedValue'),
  sizeSlider: document.getElementById('size'),
  sizeValue: document.getElementById('sizeValue'),
  colorPicker: document.getElementById('color'),
  colorValue: document.getElementById('colorValue'),
  colorPicker2: document.getElementById('color2'),
  colorValue2: document.getElementById('colorValue2'),
  gradientType: document.getElementById('gradientType'),
  shapeType: document.getElementById('shapeType'),
  textInput: document.getElementById('textInput'),
  textValue: document.getElementById('textValue'),
};


// 初始化状态
let isActive = false;

// 从存储中加载设置
chrome.storage.sync.get(['isActive', 'density', 'speed', 'size', 'color', 'color2', 'gradientType', 'shapeType', 'textValue'], (result) => {
  isActive = result.isActive || false;
  updateButtonAndStatus();

  if (result.density) elements.densitySlider.value = result.density;
  if (result.speed) elements.speedSlider.value = result.speed;
  if (result.size) elements.sizeSlider.value = result.size;

  if (result.color) elements.colorPicker.value = result.color;
  if (result.color2) elements.colorPicker2.value = result.color2;
  if (result.gradientType) elements.gradientType.value = result.gradientType;
  if (result.shapeType) elements.shapeType.value = result.shapeType;
  if (result.textValue) elements.textValue.value = result.textValue;

  updateValueDisplays();
});

// 更新按钮和状态显示
function updateButtonAndStatus() {
  elements.toggleBtn.textContent = isActive ? '关闭飘雪' : '开启飘雪';
  elements.toggleBtn.style.backgroundColor = isActive ? '#f44336' : '#4CAF50';
  elements.statusElement.textContent = isActive ? '已开启' : '已关闭';
}

// 更新数值显示
function updateValueDisplays() {
  elements.densityValue.textContent = elements.densitySlider.value;
  elements.speedValue.textContent = elements.speedSlider.value;
  elements.sizeValue.textContent = elements.sizeSlider.value;
  elements.colorValue.textContent = elements.colorPicker.value;
  elements.colorValue2.textContent = elements.colorPicker2.value;
}

// 发送配置更新到内容脚本
function sendToContentScript(option) {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      safeSendMessage(tabs[0].id, configMsg(option));
    }
  });
}

// 处理配置变化的通用函数
function configMsg(option={}) {
  return {
    ...option,
    density: parseInt(elements.densitySlider.value),
    speed: parseInt(elements.speedSlider.value),
    size: parseInt(elements.sizeSlider.value),
    color: elements.colorPicker.value,
    color2: elements.colorPicker2.value,
    gradientType: elements.gradientType.value,
    shapeType: elements.shapeType.value,
    textValue: elements.textValue.value,
  }
}

// 安全发送消息的工具函数
function safeSendMessage(tabId, message) {
  console.log('插件页打印', tabId, message); // 新增日志
  return chrome.tabs.sendMessage(tabId, message).catch(err => {
    // 忽略扩展上下文无效的错误
    if (err.message.includes('Extension context invalidated')) {
      console.log('扩展上下文已失效，无法发送消息');
      return;
    }
    // 其他错误仍然抛出
    throw err;
  });
}

// 切换飘雪状态
toggleBtn.addEventListener('click', () => {
  isActive = !isActive;
  updateButtonAndStatus();

  // 保存状态到存储
  chrome.storage.sync.set({ isActive });

  // 向内容脚本发送消息
  const option = {
    action: isActive ? 'startSnow' : 'stopSnow',
  }
  sendToContentScript(option)
});

// 监听滑块变化
elements.densitySlider.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ density: parseInt(elements.densitySlider.value) });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

elements.speedSlider.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ speed: parseInt(elements.speedSlider.value) });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

elements.sizeSlider.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ size: parseInt(elements.sizeSlider.value) });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

// 在滑块变化监听后面添加颜色变化监听
elements.colorPicker.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ color: elements.colorPicker.value });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

// 在滑块变化监听后面添加颜色变化监听
elements.colorPicker2.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ color2: elements.colorPicker2.value });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

elements.gradientType.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ gradientType: elements.gradientType.value });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

elements.shapeType.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ shapeType: elements.shapeType.value });
  elements.textInput.style.display = ['textValue','random'].includes(elements.shapeType.value) ? 'block' : 'none'
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

elements.textValue.addEventListener('input', () => {
  updateValueDisplays();
  chrome.storage.sync.set({ textValue: elements.textValue.value });
  if (!isActive) return
  const option = {
    action: 'updateSnow',
  }
  sendToContentScript(option)
});

// 2. 在页面加载时调用一次（确保DOM加载完成后）
document.addEventListener('DOMContentLoaded', () => {
  // 初始化时更新文本输入框可见性
  elements.textInput.style.display = ['textValue','random'].includes(elements.shapeType.value) ? 'block' : 'none'

  // 只有在当前是激活状态时发送启动消息
  if (isActive) {
    sendToContentScript({
      action: 'startSnow'
    });
  }
});